/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * MpmProjectController
 * 项目立项
 * <p>
 * 修改纪录
 * 2020-12-25 版本：1.0 lanjianwei 创建。
 *
 * @version 版本：1.0
 * @author 作者：lanjianwei
 * 创建日期：2020-12-25
 */

package com.topscomm.gpm.controller;

import com.topscomm.basic.exception.ServiceException;
//import com.topscomm.sd.MpmSystemConst;
//import com.topscomm.sd.controller.auto.MpmProjectControllerAuto;
//import com.topscomm.sd.pojo.MpmProjectAppointmentEntity;
//import com.topscomm.sd.pojo.MpmProjectEntity;
//import com.topscomm.mpm.pojo.MpmProjectPlanEntity;
//import com.topscomm.mpm.pojo.MpmProjectTaskEntity;
//import com.topscomm.mpm.service.*;
import com.topscomm.gpm.controller.auto.GpmProjectControllerAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.GpmProjectEntity;
import com.topscomm.gpm.service.impl.GpmProjectService;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.threadlocal.ThreadLocalContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Administrator
 * @description: 系统首页接口
 * @return:
 * @date: 2021/1/7 17:29
 */
@RestController
@RequestMapping("sd/sdIndex")
public class GpmIndexController extends GpmProjectControllerAuto {
    @Autowired
    private GpmProjectService gpmProjectService;

    /**
     * @description: 超期项目和里程碑
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/7 17:36
     */
    @GetMapping("/queryOverdueInfo")
    public ResponseResult<Object> queryOverdueInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> resultMapList = gpmProjectService.queryOverdueInfo(paraMap);
            return ResponseResult.ok(resultMapList);
        } catch(Exception ex) {
            return handleControllerException(ex);
        }

    }

    /**
     * @description: 即将超期任务查询接口
     * @param: paraMap (必传过期天数（overdueDays）)
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/8 11:16
     */
    @GetMapping("/querySoonOverdueTask")
    public ResponseResult<Object> querySoonOverdueTask(@RequestParam(required = false) Map<String, Object> paraMap) {
        //========================================== 三天/一周内过期的任务（即当前未超期，三天/一周后超期的任务）=======================
        try {
            List<Map<String, Object>> soonOverdueTaskList = gpmProjectService.querySoonOverdueTask(paraMap);
            return ResponseResult.ok(soonOverdueTaskList);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 查询近期创建或者近期完成的项目（一个月内）
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/9 15:39
     */
    @GetMapping("/queryRecentlyCreateOrComplete")
    public ResponseResult<Object> queryRecentlyCreateOrComplete(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> result = gpmProjectService.queryRecentlyCreateOrComplete(paraMap);
            return ResponseResult.ok(result);
        } catch(Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 首页echarts数据
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/11 9:28
     */
    @GetMapping("/getIndexEhartsInfo")
    public ResponseResult<Object> queryProjectLevelSatistics(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            Map<String, Object> result = gpmProjectService.queryProjectLevelSatistics(paraMap);
            return ResponseResult.ok(result);
        }  catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 获取数据看板中各个位置的组件信息
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/11 11:02
     */
    @GetMapping("/getComponentsList")
    public ResponseResult<Object> getComponentsList(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> componentsList = gpmProjectService.getComponentsList(paraMap);
            return ResponseResult.ok(componentsList);
        } catch(Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 获取数据中心组件数据(整个系统中的数据统计)
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author houyuhang
     * @date: 2021/12/20
     */
    @GetMapping("/getDataCenterInfo")
    public ResponseResult<Object> getDataCenterInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            Map<String, Object> result = gpmProjectService.getDataCenterInfo(paraMap);
            return ResponseResult.ok(result);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 获取省区金额Top10
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/13 8:38
     */
    @GetMapping("/getMoneyTop10")
    public ResponseResult<Object> getMoneyTop10(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> list = gpmProjectService.getMoneyTop10(paraMap);
            return ResponseResult.ok(list);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 获取省区项目数量Top10
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/13 10:24
     */
    @GetMapping("/getProjectCountTop10")
    public ResponseResult<Object> getProjectCountTop10(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> list = gpmProjectService.getProjectCountTop10(paraMap);
            return ResponseResult.ok(list);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 查询各个省区的项目级别数量情况
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/9/8 刘晨光 修改为简称
     */
    @GetMapping("/queryProvincesProjectLevelsCountInfo")
    public ResponseResult<Object> queryProvincesProjectLevelsInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            Map<String, Object> result = gpmProjectService.queryProvincesProjectLevelsInfo(paraMap);
            return ResponseResult.ok(result);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 数据看板上项目级别饼图信息
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/11 9:28
     */
    @GetMapping("/getDataBoardProjectLevelEhartInfo")
    public ResponseResult<Object> getDataBoardProjectLevelEhartInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            List<Map<String, Object>> listForLevel = gpmProjectService.getDataBoardProjectLevelEhartInfo(paraMap);
            return ResponseResult.ok(listForLevel);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 查询项目列表
     * @param: paraMap
     * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
     * @author Administrator
     * @date: 2021/1/13 11:14
     */
    @GetMapping("/list")
    public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            Page page = gpmProjectService.listForSdIndexController(paraMap);
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }


    /**
     * 获取综合项目信息
     * @author: houyuhang
     * @date: 2021-12-01
     * @return ResponseResult<Object>
     */
//    @GetMapping("/overallProjectInfo")
//    public ResponseResult<Object> overallProjectInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
//        try {
//            List<Map<String, Object>> echartsDataForProjectStateForMobile = mpmProjectService.overallProjectInfo(paraMap);
//            return ResponseResult.ok(echartsDataForProjectStateForMobile);
//        } catch (Exception ex) {
//            return handleControllerException(ex);
//        }
//    }
    /**
     * @author: houyuhang
     * @date: 2021-12-01
     * @description: 获取首页是否有“公司数据”的权限
     * @return: AtomicBoolean
     */
    @GetMapping("/getIndexPermission")
    public ResponseResult<Object> getIndexPermission(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            AtomicBoolean hasOrg = gpmProjectService.getIndexPermission(paraMap);
            return ResponseResult.ok(hasOrg.get());
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }

    /**
     * @description: 从线程本地副本中获取用户信息
     * @param:
     * @return: com.topscomm.tap.common.SessionUserBean
     * @author Administrator
     * @date: 2021/1/7 19:18
     */
    public SessionUserBean getUserBean() {
        return ThreadLocalContext.sessionUserBeanThreadLocal.get();
    }
    /**
     * @author: houyuhang
     * @date: 2021-12-21
     * @description: 获取任命超期/待办项目
     * @modify:
     */
    @GetMapping("/queryAppointmentOverDate")
    public ResponseResult<Object> queryAppointmentOverDate(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            String whereSql = this.spellListSqlForProject(paraMap);
            Page page = gpmProjectService.queryAppointmentOverDate(paraMap,whereSql);
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }
    /**
     * @author: houyuhang
     * @date: 2021-12-21
     * @description: 获取策划超期/待办项目
     * @modify:
     */
    @GetMapping("/queryPlanOverDate")
    public ResponseResult<Object> queryPlanOverDate(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            String whereSql = this.spellListSqlForProject(paraMap);
            Page page = gpmProjectService.queryPlanOverDate(paraMap,whereSql);
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }
    /**
     * @author: houyuhang
     * @date: 2021-12-21
     * @description: 获取项目超期
     * @modify:
     */
    @GetMapping("/queryProjectOverdue")
    public ResponseResult<Object> queryProjectOverdue(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            String whereSql = this.spellListSqlForProject(paraMap);
            Page page = gpmProjectService.queryProjectOverdue(paraMap,whereSql);
            return ResponseResult.ok(page);
        } catch (Exception ex) {
            return handleControllerException(ex);
        }
    }
    /**
     * @author: houyuhang
     * @date: 2021-12-21
     * @description:  首页信息概览超期项目、任命、策划和任命策划待办的查询条件sql拼接
     * @modify:
     */
    public String spellListSqlForProject(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" GPMPROJECT.enabled=1 ");
        // 项目名称
        if (paraMap.containsKey("qry_projectname")) {
            String value = paraMap.get("qry_projectname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and GPMPROJECT.projectname like '%{0}%' ", value);
        }
        // 项目等级
        if (paraMap.containsKey("qry_projectlevel")) {
            String value = paraMap.get("qry_projectlevel").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and GPMPROJECT.projectlevel in ({0})", value);
        }
        // 项目经理
        if (paraMap.containsKey("qry_projectmanager")) {
            String value = paraMap.get("qry_projectmanager").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (GPMPROJECT.projectmanager like '%{0}%' or GPMPROJECT.projectmanagercode like '%{0}%') ", value);
        }
        // 项目异常状态
        if (paraMap.containsKey("qry_abnormalstate")) {
            String value = paraMap.get("qry_abnormalstate").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" and abnormalstate in ({0})", value);
            }
        }
        // 项目状态
        if (paraMap.containsKey("qry_projectstate")) {
            String value = ConvertUtil.convertToString(paraMap.get("qry_projectstate"));
            if (!StringUtil.isEmpty(value)) {
                if (!value.contains(GpmSystemConst.SdProjectState.ProjectOngoing)) {
                    sql.appendSingle(" and projectstate in ({0})", value);
                } else {
                    sql.appendSingle(" and projectstate in ({0},{1})", GpmSystemConst.ProjectOngoingState, value);
                }
            }
        }
        // qry_permission org公司，inChargeMe我负责的，participate我参与的
        if (paraMap.containsKey("qry_permission")) {
            String value = (String) paraMap.get("qry_permission");
            if ("org".equals(value)) {
                sql.appendSingle(
                        " and" + gpmProjectService.spellSqlForDataBoard(new HashMap<>(), GpmProjectEntity.tableName, GpmProjectEntity.FieldId));
            } else if ("inChargeMe".equals(value)) {
                sql.appendSingle(
                        " and EXISTS (SELECT id FROM GPMPROJECT existProject WHERE existProject.ID =  {0}.{1} and existProject.PROJECTMANAGERCODE='{2}'  )",
                        GpmProjectEntity.tableName, GpmProjectEntity.FieldId, this.getUserBean().getUser().getCode());
            } else if ("participate".equals(value)) {
                // 我参与的（项目组成员中有我）
                sql.appendSingle(
                        " and EXISTS (SELECT id FROM GPMPROJECT existProject WHERE existProject.ID = {0}.{1} and EXISTS " +
                                "(SELECT ID FROM GPMPROJECTTEAM WHERE existProject.ID = GPMPROJECTTEAM.PROJECTID " +
                                "AND GPMPROJECTTEAM.USERCODE = '{2}' AND GPMPROJECTTEAM.STATE = 9  AND GPMPROJECTTEAM.ENABLED = 1)  )",
                        GpmProjectEntity.tableName, GpmProjectEntity.FieldId, this.getUserBean().getUser().getCode());
            }
        }
        // 任命、策划超期/待办字符串拼接
        if(paraMap.containsKey("qry_overdue")) {
            if(ConvertUtil.convertToInt(paraMap.get("qry_overdue")) == 1) {
                if(ConvertUtil.convertToString(paraMap.get("qry_category")).equals("appointment")) {
                    // 任命超期拼接字符串，项目立项完成时间不为空，但项目任命不存在或者只存在一条未审批完成的任命
                    sql.appendSingle("AND GPMPROJECT.FINISHDATE IS NOT NULL AND (GpmPROJECTAPPOINTMENT.ID IS NULL OR " +
                            "(GpmPROJECTAPPOINTMENT.STATE < 9 AND GpmPROJECTAPPOINTMENT.VERSION = 1))");
                } else if(ConvertUtil.convertToString(paraMap.get("qry_category")).equals("plan")) {
                    // 策划超期拼接字符串,项目任命签署时间不为空，但项目策划不存在或者只存在一条未审批完成的策划
                    sql.appendSingle("AND GpmPROJECTAPPOINTMENT.VERSION = 1 AND GpmPROJECTAPPOINTMENT.SIGNDATE IS NOT NULL AND (GpmPROJECTPLAN.ID IS NULL OR " +
                            "(GpmPROJECTPLAN.STATE < 9 AND GpmPROJECTPLAN.VERSION = 1))");
                } else {
                    throw new ServiceException("超期数据请求失败，请联系管理员");
                }
            } else if(ConvertUtil.convertToInt(paraMap.get("qry_overdue")) == 0) {
                if(ConvertUtil.convertToString(paraMap.get("qry_category")).equals("appointment")) {
                    // 任命待办拼接字符串，项目立项完成时间不为空，但项目任命不存在或者只存在一条未提交审批的任命
                    sql.appendSingle("AND GPMPROJECT.FINISHDATE IS NOT NULL AND (GpmPROJECTAPPOINTMENT.ID IS NULL OR " +
                            "(GpmPROJECTAPPOINTMENT.STATE = 0 AND GpmPROJECTAPPOINTMENT.VERSION = 1))");
                } else if(ConvertUtil.convertToString(paraMap.get("qry_category")).equals("plan")) {
                    // 策划待办拼接字符串,项目任命签署时间不为空，但项目策划不存在或者只存在一条未提交审批的策划
                    sql.appendSingle("AND GpmPROJECTAPPOINTMENT.VERSION = 1 AND GpmPROJECTAPPOINTMENT.SIGNDATE IS NOT NULL AND (GpmPROJECTPLAN.ID IS NULL OR " +
                            "(GpmPROJECTPLAN.STATE = 0 AND GpmPROJECTPLAN.VERSION = 1))");
                } else {
                    throw new ServiceException("待办数据请求失败，请联系管理员");
                }
            } else {
                throw new ServiceException("超期/待办数据请求失败，请联系管理员");
            }
        }
        return sql.toString();
    }
    /**
     * 项目超期导出excel
     *
     * @description:
     * @param paraMap
     * @param request
     * @param response
     * @author: houyuhang
     * @date: 2021年12月24日
     * @modify:
     */
    @PostMapping(value = "/exportBigExcelForIndexOverdate")
    public ResponseResult<Object> exportBigExcelForIndexOverdate(@RequestBody(required = false) Map<String, Object> paraMap,
                                                 HttpServletRequest request, HttpServletResponse response) {
        //导出参数设定
        String cols = ConvertUtil.convertToString(paraMap.get("cols"));
        String whereSql = this.spellListSqlForProject(paraMap);
        String fileName = ConvertUtil.convertToString(paraMap.get("fileName"));
        fileName = fileName.length() == 0 ? "导出数据.xlsx" : fileName + ".xlsx";
        try {
            //获得导出数据，一次导出所有页面的数据
            paraMap.put("notQueryForPageFlag", true);
            Page page = gpmProjectService.queryProjectOverdue(paraMap,whereSql);
            // 导出数据
            gpmProjectService.exportExcelXlsx(response, ResponseResult.ok(page), fileName, cols);
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

